package service

import (
	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/net/ghttp"
	"miaoyuadmin/api/backend/response"
	"net/http"
)

type middlewareService struct{}

var middleware = middlewareService{}

func Middleware() *middlewareService {
	return &middleware
}

// MiddlewareDefaultResponse is the default middleware handling handler response object and its error.
func MiddlewareDefaultResponse(r *ghttp.Request) {
	r.Middleware.Next()

	// There's custom buffer content, it then exits current handler.
	if r.Response.BufferLength() > 0 {
		return
	}

	var (
		msg  string
		err  = r.GetError()
		code = gerror.Code(err)
	)
	if err != nil {
		if code == gcode.CodeNil {
			code = gcode.CodeInternalError
		}
		msg = err.Error()
	} else if r.Response.Status > 0 && r.Response.Status != http.StatusOK {
		msg = http.StatusText(r.Response.Status)
		switch r.Response.Status {
		case http.StatusNotFound:
			code = gcode.CodeNotFound
		case http.StatusForbidden:
			code = gcode.CodeNotAuthorized
		default:
			code = gcode.CodeUnknown
		}
	} else {
		code = gcode.CodeOK
	}
	internalErr := response.CommonResp(r)
	internalErr.SetError(msg)
	internalErr.WriteJson()

}

func (s *middlewareService) CORS(r *ghttp.Request) {
	r.Response.CORSDefault()
	r.Middleware.Next()
}

//Auth jwt 登录验证中间件
func (s *middlewareService) Auth(r *ghttp.Request) {
	Auth().MiddlewareFunc()(r)

	r.Middleware.Next()
}

//Access casbin权限验证中间件
func (s *middlewareService) Access(r *ghttp.Request) {
	Access().MiddleWareFunc(r)
	r.Middleware.Next()
}
